package cn.mazexal.exambg.utils.qiniu;

import cn.hutool.core.io.FileUtil;
import cn.mazexal.exambg.models.enums.FileFrom;
import cn.mazexal.exambg.utils.MD5Utils;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 七牛云存储
 *
 * @author: Mazexal
 * Date: 2025/6/8
 */
@Component
public class QiniuOssUtil {

    @Resource
    private UploadManager uploadManager;
    @Resource
    private Auth auth;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.domain}")
    private String domain;

    // 上传文件（支持 MultipartFile）
    public String upload(MultipartFile file, FileFrom fileFrom) throws IOException {
        byte[] bytes = file.getBytes();
        String prev = fileFrom.getPrev() + "/";

        // 通过二进制流计算MD5作为文件名, 防止重复上传
        String md5 = MD5Utils.getMD5(bytes);
        // 生成唯一文件名（避免覆盖）
        String fileName = prev + md5 + "." + FileUtil.extName(file.getOriginalFilename());

        // 获取上传凭证
        String uploadToken = auth.uploadToken(bucket);

        // 执行上传
        Response response = uploadManager.put(bytes, fileName, uploadToken);
        if (!response.isOK()) {
            throw new RuntimeException("上传失败: " + response.error);
        }
        // 返回完整访问URL
        return domain + "/" + fileName;
    }


}
